package org.springcloud.plugin.framework.strategy.configuration;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import org.springcloud.plugin.framework.adapter.CoreAdapter;
import org.springcloud.plugin.framework.strategy.adapter.DiscoveryEnabledAdapter;
import org.springcloud.plugin.framework.strategy.constant.StrategyConstant;
import org.springcloud.plugin.framework.strategy.rule.DiscoveryEnabledZoneAvoidancePredicate;
import org.springcloud.plugin.framework.strategy.rule.DiscoveryEnabledZoneAvoidanceRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;

/**
 * author: yanggld
 * date: 2019/12/21 20:52
 * version: 1.0
 * description:
 * 自定义基于策略的负载均衡调用时的调用规则
 * 弃用默认的规则ZoneAvoidanceRule，org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration#ribbonRule(com.netflix.client.config.IClientConfig)
 */
@Configuration
@AutoConfigureBefore(RibbonClientConfiguration.class)//'com.netflix.client.config.IClientConfig' that could not be found.
public class StrategyLoadBalanceConfiguration {

    @Autowired
    private ConfigurableEnvironment environment;

    @Autowired
    private CoreAdapter coreAdapter;

    @Autowired(required = false)
    private DiscoveryEnabledAdapter discoveryEnabledAdapter;

    @Bean
    public IRule ribbonRule(IClientConfig config) {
        boolean zoneAvoidanceRuleEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_AVOIDANCE_RULE_ENABLED, Boolean.class, Boolean.TRUE);
        if (zoneAvoidanceRuleEnabled) {
            DiscoveryEnabledZoneAvoidanceRule discoveryEnabledRule = new DiscoveryEnabledZoneAvoidanceRule();
            discoveryEnabledRule.initWithNiwsConfig(config);

            DiscoveryEnabledZoneAvoidancePredicate discoveryEnabledPredicate = discoveryEnabledRule.getDiscoveryEnabledPredicate();
            discoveryEnabledPredicate.setPluginAdapter(coreAdapter);
            discoveryEnabledPredicate.setDiscoveryEnabledAdapter(discoveryEnabledAdapter);

            return discoveryEnabledRule;
        } else {
//            DiscoveryEnabledBaseRule discoveryEnabledRule = new DiscoveryEnabledBaseRule();
//            DiscoveryEnabledBasePredicate discoveryEnabledPredicate = discoveryEnabledRule.getDiscoveryEnabledPredicate();
//            discoveryEnabledPredicate.setPluginAdapter(pluginAdapter);
//            discoveryEnabledPredicate.setDiscoveryEnabledAdapter(discoveryEnabledAdapter);
//            return discoveryEnabledRule;
            return null;
        }
    }
}
